package com.xjm_cloud_admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjm_cloud_admin.adpater.UserVoAdapter;
import com.xjm_cloud_admin.constant.HttpStatus;
import com.xjm_cloud_admin.domain.XjmFile;
import com.xjm_cloud_admin.domain.XjmShare;
import com.xjm_cloud_admin.domain.XjmSharingFile;
import com.xjm_cloud_admin.domain.XjmUser;
import com.xjm_cloud_admin.domain.vo.req.SaveShareReqVo;
import com.xjm_cloud_admin.domain.vo.req.ShareCheckReqVo;
import com.xjm_cloud_admin.domain.vo.req.ShareDeleteReqVo;
import com.xjm_cloud_admin.domain.vo.req.ShareFileListReqVo;
import com.xjm_cloud_admin.domain.vo.resp.FileListRespVo;
import com.xjm_cloud_admin.domain.vo.resp.ShareListRespVo;
import com.xjm_cloud_admin.domain.vo.resp.ShareResp;
import com.xjm_cloud_admin.mapper.XjmShareMapper;
import com.xjm_cloud_admin.mapper.XjmSharingFileMapper;
import com.xjm_cloud_admin.redis.RedisCache;
import com.xjm_cloud_admin.security.service.ShareTokenService;
import com.xjm_cloud_admin.service.XjmFileService;
import com.xjm_cloud_admin.service.XjmFileSharingService;
import com.xjm_cloud_admin.service.XjmShareService;
import com.xjm_cloud_admin.util.IdUtils;
import com.xjm_cloud_admin.util.R;
import com.xjm_cloud_admin.util.SecurityUtils;
import com.xjm_cloud_admin.util.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 文件分享表(XjmShare)表服务实现类
 *
 * @author 浪漫写尽歌谱
 * @since 2024-04-23 18:32:32
 */
@Service("xjmShareService")
public class XjmShareServiceImpl extends ServiceImpl<XjmShareMapper, XjmShare> implements XjmShareService {
    @Resource
    private XjmShareMapper xjmShareMapper;

    @Resource
    private XjmUserServiceImpl xjmUserService;

    @Resource
    private ShareTokenService shareTokenService;

    @Resource
    private XjmFileServiceImpl xjmFileService;

    @Resource
    private XjmFileSharingService xjmFileSharingService;

    /**
     * 通过主键查询单条数据
     *
     * @param shareId 分享id
     * @return 分享文件信息
     */
    @Override
    public R getByShareId(String shareId) {
        XjmShare xjmShare = this.xjmShareMapper.selectById(shareId);
        if (xjmShare == null) {
            return R.error(HttpStatus.SHARE_INVALID, "分享已失效");
        }
        Long userId = xjmShare.getUserId();
        XjmUser user = xjmUserService.getByUserId(userId);

        Date savingTime = xjmShare.getSavingTime();
        long current = System.currentTimeMillis();
        if (current > savingTime.getTime() || "1".equalsIgnoreCase(xjmShare.getStatus())) {
            return R.error(HttpStatus.SHARE_INVALID, "分享已失效");
        }

        return R.success(UserVoAdapter.getUserAndShareInfoResp(user, xjmShare));
    }

    /**
     * 新增分享
     *
     * @param saveShareReqVo 分享信息
     * @return 结果
     */
    @Override
    @Transactional
    public R insertShare(SaveShareReqVo saveShareReqVo) {
        String id = IdUtils.randomUUIDToBase6412();
        XjmShare xjmShare = new XjmShare();
        xjmShare.setId(id);
        xjmShare.setCreateTime(new Date());
        xjmShare.setUserId(SecurityUtils.getUserId());
        xjmShare.setFileName(saveShareReqVo.getShareName());
        xjmShare.setSharePassword(saveShareReqVo.getSharePassword());
        if ("1".equals(saveShareReqVo.getType())) {
            xjmShare.setSharePassword(StringUtils.generateRandomString(4));
        }

        LocalDate now = LocalDate.now();
        switch (saveShareReqVo.getShareExpireTime()) {
            case "1":
                now = now.plusDays(7);
                break;
            case "2":
                now = now.plusDays(15);
                break;
            case "3":
                now = now.plusDays(30);
                break;
            default:
                now = now.plusDays(1);
                break;
        }
        //转换为date对象
        ZonedDateTime zonedDateTime = now.atStartOfDay(ZoneId.systemDefault());
        xjmShare.setSavingTime(Date.from(zonedDateTime.toInstant()));
        xjmShareMapper.insert(xjmShare);


        String[] ids = saveShareReqVo.getFileIds().split(",");
        List<XjmSharingFile> sharingFileList = new ArrayList<>();
        for (String s : ids) {
            XjmSharingFile xjmSharingFile = new XjmSharingFile();
            xjmSharingFile.setSharingId(xjmShare.getId());
            xjmSharingFile.setFileId(Long.parseLong(s));
            sharingFileList.add(xjmSharingFile);
        }
        xjmFileSharingService.saveBatch(sharingFileList);

        SaveShareReqVo resp = new SaveShareReqVo();
        resp.setShareName(xjmShare.getFileName());
        resp.setFileIds(xjmShare.getId());
        resp.setSharePassword(xjmShare.getSharePassword());
        return R.success().put("data", resp);
    }

    /**
     * 校验密码
     *
     * @param vo 校验信息
     * @return 校验结果
     */
    @Override
    public R checkPassword(ShareCheckReqVo vo) {
        XjmShare xjmShare = this.xjmShareMapper.selectById(vo.getShareId());

        if (xjmShare == null) {
            return R.error("分享不存在");
        }


        if (StringUtils.isEmpty(xjmShare.getSharePassword())) {
            return R.success().put("data", shareTokenService.createToken(xjmShare.getId()));
        }

        if (StringUtils.isEmpty(vo.getPassword()) || !xjmShare.getSharePassword().equals(vo.getPassword())) {
            return R.error("密码错误");
        }

        xjmShare.setLookNumber(xjmShare.getLookNumber() + 1);
        baseMapper.updateById(xjmShare);
        return R.success().put("data", shareTokenService.createToken(xjmShare.getId()));
    }

    /**
     * 获取分享的文件
     *
     * @param httpServletRequest 请求
     * @return 文件
     */
    @Override
    public R list(HttpServletRequest httpServletRequest, ShareFileListReqVo vo) {
        XjmShare share;
        String token = shareTokenService.getToken(httpServletRequest);
        if (StringUtils.isEmpty(token)) {

            return R.error("分享令牌已失效");

//
//            share = getById(vo.getShareId());
//            if (StringUtils.isNotEmpty(share.getSharePassword())) {
//            }
//            ShareListRespVo shareListRespVo = getShareListResp(share, vo);
//            return R.success(shareListRespVo);
        }
        String id = shareTokenService.verifyToken(httpServletRequest);
        if (StringUtils.isEmpty(id)) {
            return R.error("分享令牌已失效");
        }
        share = getById(vo.getShareId());
        Date savingTime = share.getSavingTime();
        long current = System.currentTimeMillis();
        if (current > savingTime.getTime() || "1".equalsIgnoreCase(share.getStatus())) {
            return R.error("分享已过期");
        }

        ShareListRespVo shareListRespVo = getShareListResp(share, vo);
        return R.success(shareListRespVo);
    }

    private ShareListRespVo getShareListResp(XjmShare share, ShareFileListReqVo vo) {
        XjmUser user = xjmUserService.getByUserId(share.getUserId());
        ShareListRespVo shareListRespVo = new ShareListRespVo();
        shareListRespVo.setFilename(shareListRespVo.getFilename());
        shareListRespVo.setNickName(user.getNickname());
        shareListRespVo.setSavingTime(share.getSavingTime());
        XjmFile topFile = xjmFileService.getById(vo.getTopId());
        if (StringUtils.isNotEmpty(vo.getParentId())) {
            List<FileListRespVo> fileListRespVos = xjmFileService.sharingTree(vo.getParentId());

            if (fileListRespVos.isEmpty()) {
                shareListRespVo.setList(new ArrayList<>());
                return shareListRespVo;
            }

            String id = "";
            if ("0".equals(topFile.getParentId().toString())) {
                id = topFile.getId().toString();
            } else {
                id = topFile.getTopId().toString();
            }
            if (!id.equals(fileListRespVos.get(0).getTopId().toString())) {
                shareListRespVo.setList(new ArrayList<>());
                return shareListRespVo;
            }

            shareListRespVo.setList(fileListRespVos);
        } else {
            String shareId = share.getId();
            List<XjmSharingFile> list = xjmFileSharingService.list(new QueryWrapper<XjmSharingFile>().lambda().eq(XjmSharingFile::getSharingId, shareId));
            List<Long> ids = list.stream().map(XjmSharingFile::getFileId).collect(Collectors.toList());
            shareListRespVo.setList(xjmFileService.getTreeByFileIds(ids));
        }

        List<FileListRespVo> collect = shareListRespVo.getList().stream().peek(item -> item.setTopId(null)).collect(Collectors.toList());
        shareListRespVo.setList(collect);
        return shareListRespVo;
    }

    /**
     * 获取分享的文件
     *
     * @return 文件
     */
    @Override
    public R shareList() {
        List<XjmShare> xjmShares = baseMapper.selectList(new QueryWrapper<XjmShare>().lambda().eq(XjmShare::getUserId, SecurityUtils.getUserId()));
        return R.success(xjmShares);
    }

    /**
     * 删除分享
     *
     * @return 文件
     */
    @Override
    public R delete(ShareDeleteReqVo vo) {
        String[] ids = vo.getShareIds().split(",");
        baseMapper.delete(new QueryWrapper<XjmShare>().lambda().in(XjmShare::getId, Arrays.asList(ids)).eq(XjmShare::getUserId, SecurityUtils.getUserId()));
        xjmFileSharingService.remove(new QueryWrapper<XjmSharingFile>().lambda().in(XjmSharingFile::getSharingId, Arrays.asList(ids)));
        return R.success();
    }

}

